package com.fresh.bus.chat.business;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.support.collections.RedisSet;
import org.springframework.stereotype.Component;

import com.fresh.bus.canoe.message.Response;
import com.fresh.bus.canoe.session.Session;
import com.fresh.bus.canoe.session.SessionRoleManager;
import com.fresh.bus.chat.ctrl.OpCodes;

@Component
public class TalkService {

	private static final Logger log = LoggerFactory
			.getLogger(TalkService.class);
	private static final Logger userLog = LoggerFactory.getLogger("userLog");
	private final StringRedisTemplate template;

	@Resource
	protected SessionRoleManager roleManager;
	@Resource
	private ScheduleManager scheduleManager;
	@Resource
	private ExperienceService expService;
	@Resource
	private UserService userService;
	@Resource
	private FriendService friendService;

	@Autowired
	public TalkService(StringRedisTemplate template) {
		this.template = template;
	}

	public Map<String, Object> requestTalk(String id, String to, String msg,
			int flowerAmt) {
		BoundHashOperations<String, String, String> ops = template
				.boundHashOps(KeyUtils.uid(id));
		ops.put("friendDesc", msg);

		Map<String, String> mine = new HashMap<String, String>();
		mine.putAll(ops.entries());
		Map<String, String> f1 = this.friendService.friend(id, to);
		if (f1.size() > 0) {
			mine.put("sendAssoValue", f1.get("assoValue"));
		} else {
			mine.put("sendAssoValue", "0");
		}
		Map<String, String> f2 = this.friendService.friend(to, id);
		if (f2.size() > 0) {
			mine.put("sendName", f2.get("nikeName"));
		} else {
			mine.put("sendName", mine.get("id"));
		}

		mine.put("friendDesc", msg);
		mine.put("sendFlowers", String.valueOf(flowerAmt));

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("user", mine);
		map.put("report", userService.findReport(id));
		return map;
	}

	public void startTalk(String me, String to) {

		Session session = roleManager.getSession(me);
		String rid = (String) session.getAttribute("rid");
		Response response = new Response(OpCodes.START_TALK);

		BoundHashOperations<String, String, String> ops = template
				.boundHashOps(KeyUtils.rid(rid));
		int t = Integer.valueOf(ops.get("talker"));
		t++;
		ops.put("talker", String.valueOf(t));
		Map<String, String> room = ops.entries();
		
		// 设置对方
		Session toSession = roleManager.getSession(to);
		toSession.setAttribute("to", me);
		toSession.setAttribute("startTalkTime", System.currentTimeMillis());
		toSession.setAttribute("isTalking", "true");
		//this.scheduleManager.leftQueue(toSession);

		Map<String, String> u1 = userService.findUser(me);
		Map<String, String> r1 = userService.findReport(me);

		Map<String, Object> map1 = new HashMap<String, Object>();
		if (friendService.friend(to, me).size() > 0) {
			map1.put("isFriend", true);
		}
		map1.put("user", u1);
		map1.put("report", r1);
		map1.put("room", room);
		response.setData(map1);
		toSession.send(response);

		// 设置自己
		session.setAttribute("to", to);
		session.setAttribute("startTalkTime", System.currentTimeMillis());
		session.setAttribute("isTalking", "true");
		//this.scheduleManager.leftQueue(session);

		Map<String, String> u2 = userService.findUser(to);
		Map<String, String> r2 = userService.findReport(to);

		Map<String, Object> map2 = new HashMap<String, Object>();
		if (friendService.friend(me, to).size() > 0) {
			map2.put("isFriend", true);
		}
		map2.put("user", u2);
		map2.put("report", r2);
		map2.put("room", room);
		response.setData(map2);
		session.send(response);

		// scheduleManager.synWaiterNum(rid);
	}

	public void endTalk(Session session, Boolean isNormal) {
		String from = session.getRole().getId();
		String to = (String) session.getAttribute("to");
		String sid = (String) session.getAttribute("sid");
		String rid = (String) session.getAttribute("rid");
		
		//记录日志
		long startTime = (Long) session.getAttribute("startTalkTime");
		long endTime = System.currentTimeMillis();
		int talkLen = (int) ((endTime - startTime) / (1000 * 60));
		MDC.put("actionDesc", from+","+ to +","+talkLen);  
		userLog.info(String.valueOf(OpCodes.END_TALK)); 

		BoundHashOperations<String, String, String> ops = template
				.boundHashOps(KeyUtils.rid(rid));
		int t = Integer.valueOf(ops.get("talker"));
		t--;
		ops.put("talker", String.valueOf(t));

		Response response = new Response(OpCodes.END_TALK);

		Session sio1 = roleManager.getSession(to);
		if (sio1.getAttribute("isTalking") != null) {
			// sio1.removeAttribute("to");
			sio1.removeAttribute("isTalking");
			//sio1.removeAttribute("rid");

			expService.update(sio1, null, OpCodes.END_TALK);
			response.setData("userLeave");
			sio1.send(response);
		}
		// 清除数据
		// session.removeAttribute("to");
		session.removeAttribute("isTalking");
		//session.removeAttribute("rid");

		if (isNormal) {
			// 增加经验
			expService.update(session, null, OpCodes.END_TALK);
			// scheduleManager.offBus(session, lid);
			response.setData("");
			session.send(response);
		}
	}
}
